package com.yanq.liancar.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import com.vondear.rxtool.RxSPTool;
import com.vondear.rxtool.view.RxToast;
import com.yanq.liancar.R;
import com.yanq.liancar.bean.BaseBean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.bean.loginUserBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.ToastUtil;
import com.yanq.liancar.util.Utils;

import butterknife.BindView;
import butterknife.ButterKnife;


public class LoginActivity extends AppCompatActivity implements View.OnClickListener {


    @BindView(R.id.back_btn)
    ImageView backBtn;
    @BindView(R.id.gang)
    TextView gang;
    @BindView(R.id.phone_num)
    EditText phoneNum;
    @BindView(R.id.password)
    EditText password;
    @BindView(R.id.forget_password)
    TextView forgetPassword;
    @BindView(R.id.register)
    TextView register;
    @BindView(R.id.tv)
    TextView tv;
    @BindView(R.id.login_btn)
    TextView login_btn;
    @BindView(R.id.img_weichat)
    ImageView img_weichat;

    private static  final  String APP_ID="wxd2e19fc6b6f17ec0";
    private IWXAPI api;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        Utils.setStatusBar(this, false, false);
        findViewById(R.id.register).setOnClickListener(this);
        findViewById(R.id.forget_password).setOnClickListener(this);
        findViewById(R.id.login_btn).setOnClickListener(this);
        findViewById(R.id.back_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    finish();
            }
        });
        img_weichat.setOnClickListener(this);
    }

    private void WXLogin(){
        api= WXAPIFactory.createWXAPI(this,APP_ID,true);
        api.registerApp(APP_ID);
        // 判断是否安装了微信客户端
        if (!api.isWXAppInstalled()) {
            RxToast.error("您还未安装微信客户端！");
        }else {
            RxSPTool.putString(this, "WeChatType","login");
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "wechat_sdk_demo";
            api.sendReq(req);
            finish();
        }


    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.register:
                startActivity(new Intent(this, RegesterActivity.class));
                break;
            case R.id.forget_password:
                startActivity(new Intent(this, FindPwdStepOneActivity.class));
                break;
            case R.id.img_weichat:
                UserBean.removeBToken(this);
                WXLogin();
                break;
            case R.id.login_btn:
                if (Utils.isMobile(phoneNum.getText().toString().trim())){
                    UserBean.removeBToken(this);
                    initOkGo();
                }else {
                    RxToast.error("请输入正确电话号码");
                }
                break;
        }

    }

    /*会员登录*/
    private void initOkGo() {
        OkGo.<String>post(Config.s + "llc/loginUser")
                .tag(this)
                .params("tel", phoneNum.getText().toString().trim())
                .params("password", password.getText().toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        loginUserBean bean = gson.fromJson(response.body(), loginUserBean.class);
                        if (bean.isIsSuccess()) {
                            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                            // 隐藏软键盘
                            imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                            LogUtils.e("1111111",bean.getData().getToken());
                            UserBean.setID(LoginActivity.this, bean.getData().getUser().getUid());
                            RxSPTool.putString(LoginActivity.this, "UserPhone", bean.getData().getUser().getTel());
                            UserBean.setcToken(LoginActivity.this, bean.getData().getToken());
                            UserBean.setName(LoginActivity.this, bean.getData().getUser().getUsername());
                            UserBean.setSign(LoginActivity.this, bean.getData().getUser().getSign());
                            UserBean.setRoleId(LoginActivity.this, bean.getData().getUser().getRoleId());
                            pushPhoneToken();
                            Intent intent=new Intent(LoginActivity.this, MinUserMainActivity.class);
                            //清空activity栈
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.putExtra("type", 4);
                            startActivity(intent);
//
//                            if (UserBean.getRoleId(LoginActivity.this)==1){         //去小C
//                                Intent intent=new Intent(LoginActivity.this, MinUserMainActivity.class);
//                                //清空activity栈
//                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
//                                intent.putExtra("type",4);
//                                startActivity(intent);
//                            }else if (UserBean.getRoleId(LoginActivity.this)==2){   //去大C
//                                Intent intent=new Intent(LoginActivity.this, CMainActivity.class);
//                                //清空activity栈
//                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
//                                startActivity(intent);
//                            }
                            finish();
                        } else {
                            RxToast.error(bean.getOutputMessage());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        RxToast.error("服务器连接失败");
                        LogUtils.e("asdasdad",response.code()+"");
                        LogUtils.e("asdasdad",response.message()+"");
                        if (response.code()==-1){   //服务器连接不成功

                        }

                        super.onError(response);
                    }
                });
    }

    private void pushPhoneToken() {
        OkGo.<String>post(Config.s + "llc/pushController/addPushTokenForUser")
                .tag(this)
                .params("token",UserBean.getcToken(this))
                .params("pushToken", UserBean.getPushToken(this))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBean baseBean=gson.fromJson(response.body(),BaseBean.class);
                        if (baseBean.isIsSuccess()){
                        } else {
                            RxToast.error(baseBean.getOutputMessage());
                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        RxToast.error("服务器连接失败");
                        LogUtils.e("asdasdad",response.code()+"");
                        LogUtils.e("asdasdad",response.message()+"");
                        super.onError(response);
                    }
                });
    }
}

